package com.zhsj.OkeHomeConsumption.other;

import android.os.Handler;
import android.os.Message;
import android.util.Log;


import java.util.Timer;
import java.util.TimerTask;


/**
* @ClassName: TimeChecker 
* @Description: TODO 计时器类，处理耗时操作的超时管理
* @author zhangpeisen
* @date 2016年9月13日 下午3:29:40 
*/
public class TimeChecker {
	
	private int hodingTime = 0;
	private final int copyTime;
	private Handler handler = null;
	private int flag = 0;
	public static final int TIME_BREAK = 900;
	public static final int TIME_OUT = 901;

	/**
	 * 构造函数
	 * 
	 * @param handler
	 *            超时提示回调handler
	 * @param hodingTime
	 *            计时时间
	 */
	public TimeChecker(Handler handler, int hodingTime) {
		this.hodingTime = hodingTime;
		this.handler = handler;
		copyTime = hodingTime;
		flag = 0;
	}

	/**
	 * 记时开始时调用，自动倒计时，从hodingtime到0为止，到0仍未被打断则向handler发送超时信息
	 */
	public void start() {
		flag = 0;
		hodingTime = copyTime;
		final Timer time = new Timer();
		time.schedule(new TimerTask() {
			@Override
			public void run() {
				if (hodingTime != 0) {
					if (flag == 1) {
						time.cancel();
						Message msg = new Message();
						msg.what = TIME_BREAK;
						handler.sendMessage(msg);
						 Log.i("TimeChecker", "计时中断。");
					} else {
						 Log.i("TimeChecker", "继续计时：" + hodingTime);
						hodingTime--;
					}
				} else {
					time.cancel();
					if (flag != 1) {
						flag = 1;
						Message msg = new Message();
						msg.what = TIME_OUT;
						handler.sendMessage(msg);
					} else {
						// TODO
					}
				}
			}
		}, 0, 3000);
	}

	/**
	 * 检查是否超时，未超时则打断记时使用数据，已超时则放弃数据
	 * 
	 * @return true：未超时，可以使用数据，false:已超时，返回数据废弃
	 */
	public boolean check() {
		if (flag == 0) {
			flag = 1;
			Log.i("TimeChecker", "数据使用");
			return true;
		} else if (flag == 1) {
			Log.i("TimeChecker", "已超时数据不使用");
			return false;
		} else {
			return false;
		}
	}
}
